﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Text;
using System.Windows.Forms;
using AutoItX3Lib;
using System.IO;
using System.Xml;
using System.Configuration;

namespace RouletteD5
{
    public partial class VegasBOT : Form
    {
        private delegate void PlayGame();

        private AutoItX3 autoit = new AutoItX3();
        private bool Game_Busy = true;
        private string WIN_TITLE = "";
        IntPtr HANDLER;
        private string IMAGE_PATH = "";
        private GAME_STATUS STATUS = GAME_STATUS.READY;
        private int BalanceAmount = 0;
        private int STOP_WIN_AMOUNT = 0;
        private int STOP_LOSE_AMOUNT = 0;
        private int KEEP_ALIVE_AMOUNT = 0;
        private int CurrStrategy = 1;
        private List<OTHER_STRATEGY_TYPE> otherStrategyData;
        private List<FOLLOW_STRATEGY_TYPE> followStrategyData;
        private int LAST_WIN_NUMBER = 0;
        private int[] RedNumber = { 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 };
        private int[] BlackNumber = { 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35 };
        private int[] Column1Number = { 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34 };
        private int[] Column2Number = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 };
        private int[] Column3Number = { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36 };
        private int[] Dozen1Number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
        private int[] Dozen2Number = { 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
        private int[] Dozen3Number = { 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 };
        private int HighNumber = 19;
        private bool IsKeepAlive = false;
        private int[,] betInfo;

        const int ORG_POSX = 0;
        const int ORG_POSY = 30;
        const string IMAGE_READY = "Ready.jpg";
        const string IMAGE_NO_MORE_BET = "NoMoreBet.jpg";        
        const int IMG_WIDTH = 15;
        const int IMG_HEIGH = 15;

        enum GAME_STATUS
        {
            READY = 1,
            NOMOREBET = 2,
            WINNER = 3
        }

        enum STRATEGY
        {
            BLACK_RED = 0,
            EVEN_ODD = 1,
            HIGH_LOW = 2,
            COLUMNS = 3,
            DOZENS = 4,            
            NUMBER = 5
        }
        enum SUB_STRATEGY
        {
            BLACK = 0,
            RED = 1,
            HIGH = 2,
            LOW = 3,
            EVEN = 4,
            ODD = 5,
            D1 = 6,
            D2 = 7,
            D3 = 8,
            C1 = 9,
            C2 = 10,
            C3 = 11,
            NUMBER = 12
        }

        struct NUMBER_TYPE
        {
            public int NotHintTime;            
            public int[] BetValueList;
        }

        struct OTHER_STRATEGY_TYPE
        {
            public STRATEGY Strategy;
            public SUB_STRATEGY SubStrategy;
            public int Wait;
            public int NotHintTime;
            public List<NUMBER_TYPE> Number;
        }

        struct FOLLOW_STRATEGY_TYPE
        {
            public STRATEGY Strategy;
            public int NoOfMiss;
            public int[] BetValueList;
        }

                
        public VegasBOT()
        {
            InitializeComponent();
        }

        private void VegasBOT_Load(object sender, EventArgs e)
        {
            IMAGE_PATH = Path.Combine(Application.StartupPath, "Image");
            LoadDataconfig();
        }
            
        private void btnCofiguration_Click(object sender, EventArgs e)
        {
            FrmConfiguration frm = new FrmConfiguration();
            if (frm.InitForm()) frm.ShowDialog();
            frm = null;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                this.HANDLER = this.browserGame.Handle;
                STATUS = GAME_STATUS.READY;
                Game_Busy = false;
                WIN_TITLE = this.Text;
                IsKeepAlive = chkKeepAlive.Checked;
                txtUrl.Enabled = false;
                BalanceAmount = 0;
                LAST_WIN_NUMBER = -2;
                LoadDataconfig();

                btnStart.Enabled = false;
                btnCofiguration.Enabled = false;
                btnStop.Enabled = true;
                btnPlayGame.Enabled = false;
                chkKeepAlive.Enabled = false;

                Application.DoEvents();
                
                PlayGame myGame = new PlayGame(Play);
                myGame.BeginInvoke(CallbackBOT, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Play()
        {
            switch (STATUS)
            {
                case GAME_STATUS.READY:
                    if (IsReady())
                    {   
                     
                        System.Threading.Thread.Sleep(3000);
                        Application.DoEvents();

                        //click on 1$ icon
                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, 188, 347);

                        bool notPlace = true;
                        PlaceBet(out notPlace);

                        if (IsKeepAlive && notPlace)
                        {
                            System.Threading.Thread.Sleep(100);
                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", KEEP_ALIVE_AMOUNT, 196, 313);                            
                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", KEEP_ALIVE_AMOUNT, 250, 313);
                        }
                        
                        STATUS = GAME_STATUS.NOMOREBET;
                    }
                    break;

                case GAME_STATUS.NOMOREBET:
                    if (IsNomoreBet())
                        STATUS = GAME_STATUS.WINNER;
                    break;

                case GAME_STATUS.WINNER:
                    if (IsReady())
                    {   
                        CalculateAndUpdateUI();
                        STATUS = GAME_STATUS.READY;
                    }

                    break;

                default: break;
            }
        }

        private void CallbackBOT(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                try
                {
                    PlayGame worker = (PlayGame)((AsyncResult)result).AsyncDelegate;
                    worker.EndInvoke(result);

                    if (!Game_Busy) 
                    {
                        if (BalanceAmount >= STOP_WIN_AMOUNT || Math.Abs(BalanceAmount) >= Math.Abs(STOP_LOSE_AMOUNT))
                        {
                            Game_Busy = true;                            
                        }
                        else
                        {
                            PlayGame myGame = new PlayGame(Play);
                            myGame.BeginInvoke(CallbackBOT, null);
                        }
                    }
                }
                catch
                {
                    if (!Game_Busy)
                    {
                        if (BalanceAmount >= STOP_WIN_AMOUNT || Math.Abs(BalanceAmount) >= Math.Abs(STOP_LOSE_AMOUNT))
                        {
                            Game_Busy = true;                            
                        }
                        else
                        {
                            PlayGame myGame = new PlayGame(Play);
                            myGame.BeginInvoke(CallbackBOT, null);
                        }
                    }
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Game_Busy = true;
            btnStart.Enabled = true;
            btnCofiguration.Enabled = true;
            btnStop.Enabled = false;
            btnPlayGame.Enabled = true;
            chkKeepAlive.Enabled = true;
            txtUrl.Enabled = true;
        }

        #region "implement the behaviour of bot"

        private bool IsReady()
        {
            return IsMatch(IMAGE_READY, "IsReady.jpg", 10, 335, 15, 15);
        }

        private bool IsNomoreBet()
        {
            return IsMatch(IMAGE_NO_MORE_BET, "IsNomoreBet.jpg", 10, 335, 15, 15);
        }

        private int WinnerNumber()
        {            
            //zero number position
            var match = false;
            //var match = IsMatch("Zero.jpg", "IsZero.jpg", 100, 100, 10, 10);
            //if (match) return 0;

            int posX = 64, posY = 172;
            int verticalMargin = 28, horizonalMargin = 40;
            int counter = 0;
            for (int i = 1; i <= 12; i++)
            {
                posY = 172;
                counter = 3 * i;
                for (int j = 3; j > 0; j--)
                {
                    match = IsMatch(string.Format("N{0}.jpg", counter), string.Format("IsN{0}.jpg", counter), posX, posY, 10, 10);
                    if (match) return counter;

                    posY += horizonalMargin;
                    counter--;
                }
                posX = posX + verticalMargin;
            }

            return -2;
        }

        private void CalculateAndUpdateUI()
        {
            LAST_WIN_NUMBER = WinnerNumber();

            if (betInfo == null) betInfo = new int[50, 1];

            if (CurrStrategy == 1)
            {
                var tempData = otherStrategyData.ToArray();
                for (int j = 0; j < tempData.Length; j++)
                {
                    switch (tempData[j].SubStrategy)
                    {
                        case SUB_STRATEGY.BLACK:
                            if (BlackNumber.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.BLACK, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.BLACK, 0];
                            }
                            break;

                        case SUB_STRATEGY.RED:
                            if (RedNumber.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.RED, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.RED, 0];
                            }
                            break;

                        case SUB_STRATEGY.HIGH:
                            if (LAST_WIN_NUMBER >= HighNumber)
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.HIGH, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.HIGH, 0];
                            }
                            break;

                        case SUB_STRATEGY.LOW:
                            if (LAST_WIN_NUMBER < HighNumber && LAST_WIN_NUMBER > 0)
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.LOW, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.LOW, 0];
                            }
                            break;

                        case SUB_STRATEGY.EVEN:
                            if (LAST_WIN_NUMBER % 2 == 0 && LAST_WIN_NUMBER > 0)
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.EVEN, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.EVEN, 0];
                            }
                            break;

                        case SUB_STRATEGY.ODD:
                            if (LAST_WIN_NUMBER % 2 != 0 && LAST_WIN_NUMBER > 0)
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.ODD, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.ODD, 0];
                            }
                            break;

                        case SUB_STRATEGY.D1:
                            if (Dozen1Number.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.D1, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.D1, 0];
                            }
                            break;

                        case SUB_STRATEGY.D2:
                            if (Dozen2Number.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.D2, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.D2, 0];
                            }
                            break;

                        case SUB_STRATEGY.D3:
                            if (Dozen3Number.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.D3, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.D3, 0];
                            }
                            break;

                        case SUB_STRATEGY.C1:
                            if (Column1Number.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.C1, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.C1, 0];
                            }
                            break;

                        case SUB_STRATEGY.C2:
                            if (Column2Number.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.C2, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.C2, 0];
                            }
                            break;

                        case SUB_STRATEGY.C3:
                            if (Column3Number.Contains(LAST_WIN_NUMBER))
                            {
                                tempData[j].NotHintTime = 0;
                                BalanceAmount += betInfo[(int)SUB_STRATEGY.C3, 0];
                            }
                            else
                            {
                                tempData[j].NotHintTime++;
                                BalanceAmount -= betInfo[(int)SUB_STRATEGY.C3, 0];
                            }
                            break;

                        default: //number                            
                            var tempNumber = tempData[j].Number.ToArray();
                            for (int i = 0; i < tempNumber.Length; i++)
                            {
                                if (i == LAST_WIN_NUMBER + 2)
                                {
                                    tempNumber[i].NotHintTime = 0;
                                    BalanceAmount += betInfo[i + 11, 0];
                                }
                                else
                                {
                                    tempNumber[i].NotHintTime++;
                                    BalanceAmount -= betInfo[i + 11, 0];
                                }                                
                            };
                            tempData[j].Number = tempNumber.ToList();
                            break;
                    }
                }
                otherStrategyData = tempData.ToList();
            }
            else
            {
                followStrategyData.ForEach(item =>
                    {
                        switch (item.Strategy)
                        {
                            case STRATEGY.BLACK_RED:
                                if (BlackNumber.Contains(LAST_WIN_NUMBER))
                                    item.NoOfMiss++;
                                break;

                            default: break;
                        }
                    });
            }
        }

        private void PlaceBet(out bool notPlaceAnyMore)
        {
            notPlaceAnyMore = true;

            int BetAmount = 0;
            int NoOfMiss = 0;
            int posX = 68;
            bool betOnZero = false;

            betInfo = new int[50, 1];

            //do other strategy
            if (CurrStrategy == 1)
            {
                foreach (var item in otherStrategyData)
                {
                    NoOfMiss = item.NotHintTime - item.Wait;
                    if (NoOfMiss < 0 || NoOfMiss > 29) continue;

                    BetAmount = item.Number[0].BetValueList[NoOfMiss];

                    switch (item.Strategy)
                    {
                        case STRATEGY.BLACK_RED:
                            if (item.SubStrategy == SUB_STRATEGY.BLACK)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 250, 313);
                                    betInfo[(int)SUB_STRATEGY.BLACK, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < BlackNumber.Length; i++)
                                {
                                    BetAmount = item.Number[BlackNumber[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(BlackNumber[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (BlackNumber[i] / 3) * 28, 262);
                                        else if (Column2Number.Contains(BlackNumber[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (BlackNumber[i] / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((BlackNumber[i] / 3) - 1) * 28, 182);
                                        
                                        //put bet amount to container
                                        betInfo[BlackNumber[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            else
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 196, 313);
                                    betInfo[(int)SUB_STRATEGY.RED, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < RedNumber.Length; i++)
                                {
                                    BetAmount = item.Number[RedNumber[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(RedNumber[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (RedNumber[i] / 3) * 28, 262);
                                        else if (Column2Number.Contains(RedNumber[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (RedNumber[i] / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((RedNumber[i] / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[RedNumber[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }   
                                }
                            }
                            break;

                        case STRATEGY.HIGH_LOW:
                            if (item.SubStrategy == SUB_STRATEGY.HIGH)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 362, 313);
                                    betInfo[(int)SUB_STRATEGY.HIGH, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 19; i <= 36; i++)
                                {
                                    BetAmount = item.Number[i + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 262);
                                        else if (Column2Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((i / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[i + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    } 
                                }
                            }
                            else
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 82, 311);
                                    betInfo[(int)SUB_STRATEGY.LOW, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 1; i <= 18; i++)
                                {
                                    BetAmount = item.Number[i + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 262);
                                        else if (Column2Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((i / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[i + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            break;

                        case STRATEGY.EVEN_ODD:
                            if (item.SubStrategy == SUB_STRATEGY.EVEN)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 138, 313);
                                    betInfo[(int)SUB_STRATEGY.EVEN, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 2; i <= 36; i += 2)
                                {
                                    BetAmount = item.Number[i + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 262);
                                        else if (Column2Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((i / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[i + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            else
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 304, 313);
                                    betInfo[(int)SUB_STRATEGY.ODD, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 1; i <= 36; i += 2)
                                {
                                    BetAmount = item.Number[i + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 262);
                                        else if (Column2Number.Contains(i))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((i / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[i + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            break;

                        case STRATEGY.DOZENS:
                            if (item.SubStrategy == SUB_STRATEGY.D1)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 112, 293);
                                    betInfo[(int)SUB_STRATEGY.D1, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < Dozen1Number.Length; i++)
                                {
                                    BetAmount = item.Number[Dozen1Number[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        if (Column1Number.Contains(Dozen1Number[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Dozen1Number[i] / 3) * 28, 262);
                                        else if (Column2Number.Contains(Dozen1Number[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Dozen1Number[i] / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((Dozen1Number[i] / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[Dozen1Number[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            else if (item.SubStrategy == SUB_STRATEGY.D2)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 224, 292);
                                    betInfo[(int)SUB_STRATEGY.D2, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < Dozen2Number.Length; i++)
                                {
                                    BetAmount = item.Number[Dozen2Number[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        //System.Threading.Thread.Sleep(50);

                                        if (Column1Number.Contains(Dozen2Number[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Dozen2Number[i] / 3) * 28, 262);
                                        else if (Column2Number.Contains(Dozen2Number[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Dozen2Number[i] / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((Dozen2Number[i] / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[Dozen2Number[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            else
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 332, 291);
                                    betInfo[(int)SUB_STRATEGY.D3, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < Dozen3Number.Length; i++)
                                {
                                    BetAmount = item.Number[Dozen3Number[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        //System.Threading.Thread.Sleep(50);

                                        if (Column1Number.Contains(Dozen3Number[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Dozen3Number[i] / 3) * 28, 262);
                                        else if (Column2Number.Contains(Dozen3Number[i]))
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Dozen3Number[i] / 3) * 28, 220);
                                        else
                                            autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((Dozen3Number[i] / 3) - 1) * 28, 182);

                                        //put bet amount to container
                                        betInfo[Dozen3Number[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }

                            BetAmount = item.Number[2].BetValueList[NoOfMiss];
                            if (betOnZero == false && BetAmount > 0)
                            {
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX - 20, 220);
                                betInfo[49, 0] += BetAmount;
                                betOnZero = true;
                            }

                            break;

                        case STRATEGY.COLUMNS:                            
                            if (item.SubStrategy == SUB_STRATEGY.C1)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 400, 262);
                                    betInfo[(int)SUB_STRATEGY.C1, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < Column1Number.Length; i++)
                                {
                                    BetAmount = item.Number[Column1Number[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Column1Number[i] / 3) * 28, 262);
                                        //put bet amount to container
                                        betInfo[Column1Number[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            else if (item.SubStrategy == SUB_STRATEGY.C2)
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 400, 220);
                                    betInfo[(int)SUB_STRATEGY.C2, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < Column2Number.Length; i++)
                                {
                                    BetAmount = item.Number[Column2Number[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (Column2Number[i] / 3) * 28, 220);
                                        //put bet amount to container
                                        betInfo[Column2Number[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }
                            else
                            {
                                //bet on the head of strategy                            
                                if (BetAmount > 0)
                                {
                                    autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                                    betInfo[(int)SUB_STRATEGY.C3, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }

                                for (int i = 0; i < Column3Number.Length; i++)
                                {
                                    BetAmount = item.Number[Column3Number[i] + 2].BetValueList[NoOfMiss];
                                    if (BetAmount > 0)
                                    {
                                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((Column3Number[i] / 3) - 1) * 28, 182);
                                        //put bet amount to container
                                        betInfo[Column3Number[i] + 11, 0] += BetAmount;
                                        notPlaceAnyMore = false;
                                    }
                                }
                            }

                            BetAmount = item.Number[2].BetValueList[NoOfMiss];
                            if (betOnZero == false && BetAmount > 0)
                            {
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX - 20, 220);
                                betInfo[49, 0] += BetAmount;
                                betOnZero = true;
                            }

                            break;

                        case STRATEGY.NUMBER:
                            for (int i = 3; i <= 38; i++)
                            {
                                NoOfMiss = item.Number[i].NotHintTime - item.Wait;
                                if (NoOfMiss < 0 || NoOfMiss > 29) continue;

                                BetAmount = item.Number[i].BetValueList[NoOfMiss];
                                if (BetAmount > 0)
                                {
                                    if (Column1Number.Contains(i))
                                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 262);
                                    else if (Column2Number.Contains(i))
                                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + (i / 3) * 28, 220);
                                    else
                                        autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, posX + ((i / 3) - 1) * 28, 182);

                                    //put bet amount to container
                                    betInfo[i + 9, 0] += BetAmount;
                                    notPlaceAnyMore = false;
                                }
                            }
                            break;

                        default: break;
                    }
                }
            }
            else //do following strategy
            {
                if (LAST_WIN_NUMBER <= 0) return;
                foreach (var item in followStrategyData)
                {
                    BetAmount = item.BetValueList[item.NoOfMiss];
                    if (BetAmount <= 0) continue;

                    switch (item.Strategy)
                    {
                        case STRATEGY.BLACK_RED:
                            if (RedNumber.Contains(LAST_WIN_NUMBER))
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                            else if (BlackNumber.Contains(LAST_WIN_NUMBER))
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                            break;

                        case STRATEGY.HIGH_LOW:
                            if (HighNumber <= LAST_WIN_NUMBER)
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                            else if (0 < LAST_WIN_NUMBER)
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                            break;

                        case STRATEGY.EVEN_ODD:
                            if(LAST_WIN_NUMBER%2==0)
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                            else
                                autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", BetAmount, 100, 100);
                            break;

                        default: break;
                    }
                }
            }

            //click on reset bet for testing
            //autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, 399, 340);
        }

        private void LoadDataconfig()
        {
            try
            {
                var dataFilePath = Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["DataFilePath"]);
                if (!File.Exists(dataFilePath)) return;
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(dataFilePath);

                STOP_WIN_AMOUNT = Convert.ToInt32(xmlDoc.DocumentElement.FirstChild.InnerText);
                STOP_LOSE_AMOUNT = Convert.ToInt32(xmlDoc.DocumentElement.ChildNodes[1].InnerText);
                KEEP_ALIVE_AMOUNT = Convert.ToInt32(xmlDoc.DocumentElement.ChildNodes[2].InnerText);
                CurrStrategy = Convert.ToInt32(xmlDoc.DocumentElement.ChildNodes[3].InnerText);

                //load data for other strategy data
                otherStrategyData = new List<OTHER_STRATEGY_TYPE>();
                XmlNode rootNode = xmlDoc.DocumentElement.LastChild;
                OTHER_STRATEGY_TYPE strategyType;
                NUMBER_TYPE numberType;
                
                for (int i = 0; i <= 5; i++)
                {
                    strategyType = new OTHER_STRATEGY_TYPE();
                    strategyType.Strategy = (STRATEGY)i;

                    switch (strategyType.Strategy)
                    {
                        case STRATEGY.BLACK_RED: strategyType.SubStrategy = SUB_STRATEGY.BLACK; break;
                        case STRATEGY.HIGH_LOW: strategyType.SubStrategy = SUB_STRATEGY.HIGH; break;
                        case STRATEGY.EVEN_ODD: strategyType.SubStrategy = SUB_STRATEGY.EVEN; break;
                        case STRATEGY.DOZENS: strategyType.SubStrategy = SUB_STRATEGY.D1; break;
                        case STRATEGY.COLUMNS: strategyType.SubStrategy = SUB_STRATEGY.C1; break;
                        case STRATEGY.NUMBER: strategyType.SubStrategy = SUB_STRATEGY.NUMBER; break;
                    }

                    strategyType.Wait = Convert.ToInt32(rootNode.ChildNodes[i].FirstChild.InnerText);
                    strategyType.NotHintTime = 0;
                    strategyType.Number = new List<NUMBER_TYPE>();
                    for (int j = 0; j <= 38; j++)
                    {
                        numberType = new NUMBER_TYPE
                        {
                            NotHintTime = 0,
                            BetValueList = Array.ConvertAll(rootNode.ChildNodes[i].ChildNodes[j + 1].InnerText.Split(";".ToCharArray()), int.Parse)
                        };
                        strategyType.Number.Add(numberType);                        
                    }
                    otherStrategyData.Add(strategyType);
                }
                var red = otherStrategyData.First(s => s.Strategy == STRATEGY.BLACK_RED);
                red.SubStrategy = SUB_STRATEGY.RED;
                otherStrategyData.Insert(1, red);
                
                var highIndex = otherStrategyData.FindIndex(s => s.Strategy == STRATEGY.HIGH_LOW);
                var low = otherStrategyData.ElementAt(highIndex);
                low.SubStrategy = SUB_STRATEGY.LOW;
                otherStrategyData.Insert(highIndex + 1, low);

                var evenIndex = otherStrategyData.FindIndex(s => s.Strategy == STRATEGY.EVEN_ODD);
                var odd = otherStrategyData.ElementAt(evenIndex);
                odd.SubStrategy = SUB_STRATEGY.ODD;
                otherStrategyData.Insert(evenIndex + 1, odd);

                var dozenIndex = otherStrategyData.FindIndex(s => s.Strategy == STRATEGY.DOZENS);
                var D2 = otherStrategyData.ElementAt(dozenIndex);
                D2.SubStrategy = SUB_STRATEGY.D2;
                otherStrategyData.Insert(dozenIndex + 1, D2);
                D2.SubStrategy = SUB_STRATEGY.D3;
                otherStrategyData.Insert(dozenIndex + 2, D2);

                var columnIndex = otherStrategyData.FindIndex(s => s.Strategy == STRATEGY.COLUMNS);
                var C2 = otherStrategyData.ElementAt(columnIndex);
                C2.SubStrategy = SUB_STRATEGY.C2;
                otherStrategyData.Insert(columnIndex + 1, C2);
                C2.SubStrategy = SUB_STRATEGY.C3;
                otherStrategyData.Insert(columnIndex + 2, C2);

                //load data for follow strategy data
                followStrategyData = new List<FOLLOW_STRATEGY_TYPE>();
                rootNode = xmlDoc.DocumentElement.ChildNodes[4];
                FOLLOW_STRATEGY_TYPE flwData;
                for (int i = 0; i <= 2; i++)
                {
                    flwData = new FOLLOW_STRATEGY_TYPE();                    
                    flwData.Strategy = (STRATEGY)i;
                    flwData.NoOfMiss = 0;
                    flwData.BetValueList = Array.ConvertAll(rootNode.ChildNodes[i].InnerText.Split(";".ToCharArray()), int.Parse);

                    followStrategyData.Add(flwData);
                }

                xmlDoc = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ChangeTitle(string title, Control ctrl)
        {
            if (ctrl.InvokeRequired)
                ChangeTitle(title, ctrl);
            else
                ctrl.Text = title;
        }

        private void SetEnableControl(Control ctrl, bool state)
        {
            if (ctrl.InvokeRequired)
                SetEnableControl(ctrl, state);
            else
                ctrl.Enabled = state;
        }
                
        private bool IsMatch(Image currentCard, string cardFileName)
        {
            var card = Image.FromFile(cardFileName);
            var isMatch = card.EqualTo(currentCard);

            card.Dispose();
            card = null;

            return isMatch;
        }

        private bool IsMatch(string orgFileName, string newName, int posX, int posY)
        {
            return IsMatch(orgFileName, newName, posX, posY, IMG_WIDTH, IMG_HEIGH);
        }

        private bool IsMatch(string orgFileName, string newName, int posX, int posY, int width, int heigh)
        {
            if (!File.Exists(Path.Combine(IMAGE_PATH, orgFileName))) return false;
            var orgImage = Image.FromFile(Path.Combine(IMAGE_PATH, orgFileName));

            var imgTemp = CaptureImage(this.HANDLER, posX, posY, width, heigh);
            imgTemp.Save(Path.Combine(IMAGE_PATH, newName));
            imgTemp.Dispose();
            imgTemp = null;
            imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, newName));

            var isMatch = orgImage.EqualTo(imgTemp);

            imgTemp.Dispose();
            imgTemp = null;
            orgImage.Dispose();
            orgImage = null;

            return isMatch;
        }

        #endregion

        #region "proccess images"

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
        public const int SRCCOPY = 13369376;

        private Image CaptureImage(IntPtr handle, int posX, int posY, int width, int height)
        {

            IntPtr hdcSrc = GetWindowDC(handle);

            IntPtr hdcDest = CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height);

            IntPtr hOld = SelectObject(hdcDest, hBitmap);
            BitBlt(hdcDest, 0, 0, width, height, hdcSrc, posX, posY, SRCCOPY);
            SelectObject(hdcDest, hOld);
            DeleteDC(hdcDest);
            ReleaseDC(handle, hdcSrc);

            Image image = Image.FromHbitmap(hBitmap);
            DeleteObject(hBitmap);

            return image;
        }

        #endregion

        #region "import DLL methods"

        [Flags]
        public enum SetWindowPosFlags : uint
        {
            // ReSharper disable InconsistentNaming

            /// <summary>
            ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
            /// </summary>
            SWP_ASYNCWINDOWPOS = 0x4000,

            /// <summary>
            ///     Prevents generation of the WM_SYNCPAINT message.
            /// </summary>
            SWP_DEFERERASE = 0x2000,

            /// <summary>
            ///     Draws a frame (defined in the window's class description) around the window.
            /// </summary>
            SWP_DRAWFRAME = 0x0020,

            /// <summary>
            ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
            /// </summary>
            SWP_FRAMECHANGED = 0x0020,

            /// <summary>
            ///     Hides the window.
            /// </summary>
            SWP_HIDEWINDOW = 0x0080,

            /// <summary>
            ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
            /// </summary>
            SWP_NOACTIVATE = 0x0010,

            /// <summary>
            ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
            /// </summary>
            SWP_NOCOPYBITS = 0x0100,

            /// <summary>
            ///     Retains the current position (ignores X and Y parameters).
            /// </summary>
            SWP_NOMOVE = 0x0002,

            /// <summary>
            ///     Does not change the owner window's position in the Z order.
            /// </summary>
            SWP_NOOWNERZORDER = 0x0200,

            /// <summary>
            ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
            /// </summary>
            SWP_NOREDRAW = 0x0008,

            /// <summary>
            ///     Same as the SWP_NOOWNERZORDER flag.
            /// </summary>
            SWP_NOREPOSITION = 0x0200,

            /// <summary>
            ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
            /// </summary>
            SWP_NOSENDCHANGING = 0x0400,

            /// <summary>
            ///     Retains the current size (ignores the cx and cy parameters).
            /// </summary>
            SWP_NOSIZE = 0x0001,

            /// <summary>
            ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
            /// </summary>
            SWP_NOZORDER = 0x0004,

            /// <summary>
            ///     Displays the window.
            /// </summary>
            SWP_SHOWWINDOW = 0x0040,

            // ReSharper restore InconsistentNaming
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);

        [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
        [DllImport("User32", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr FindWindow
        (
            [MarshalAs(UnmanagedType.LPTStr)] string lpClassName,  // class name
            [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName  // window name
        );

        #endregion

        private void btnPlayGame_Click(object sender, EventArgs e)
        {
            //validate the Url is empty or not
            if (string.IsNullOrEmpty(txtUrl.Text.Trim()))
            {
                MessageBox.Show("Please enter the Url of Roulette to play the game", "Roulettist Warning Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUrl.Focus();
                return;
            }

            //validate the format the Url is invalid or not
            if (!Uri.IsWellFormedUriString(txtUrl.Text.Trim(), UriKind.Absolute))
            {
                MessageBox.Show("The Url of Roulette is invalid. Please enter the Url correctly", "Roulettist Warning Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                txtUrl.Clear();
                txtUrl.Focus();
                return;
            }

            this.browserGame.Url = new Uri(txtUrl.Text);
            
            btnPlayGame.Enabled = false;
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                HANDLER = this.browserGame.Handle;
                Image Pictemp = CaptureImage(HANDLER, Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text), Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text));
                Pictemp.Save(Path.Combine(Application.StartupPath, "temp.jpg"));
                Pictemp.Dispose();
                Pictemp = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //AutoItX3 autoit = new AutoItX3();
                WIN_TITLE = this.Text;
                this.browserGame.Focus();
                var i = autoit.ControlClick(WIN_TITLE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "left", 1, Convert.ToInt32(textBox5.Text), Convert.ToInt32(textBox6.Text));
                MessageBox.Show(i.ToString());
                
                //autoit.ControlClick(textBox7.Text, "", "[CLASS:Chrome_RenderWidgetHostHWND; INSTANCE:1]", "LEFT", 1, Convert.ToInt32(textBox5.Text), Convert.ToInt32(textBox6.Text));
                //autoit = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }

        private void browserGame_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            btnPlayGame.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            HANDLER = this.browserGame.Handle;
            int posX = 64, posY = 172;
            int verticalMargin = 28, horizonalMargin = 40;
            int counter = 0;

            for (int i = 1; i <= 12; i++)
            {
                posY = 172;
                counter = 3 * i;
                for (int j = 3; j > 0; j--)
                {
                    Image Pictemp = CaptureImage(HANDLER, posX, posY, 10, 10);
                    Pictemp.Save(Path.Combine(Application.StartupPath, string.Format("N{0}.jpg", counter)));
                    Pictemp.Dispose();
                    Pictemp = null;

                    posY += horizonalMargin;
                    counter--;
                }
                posX = posX + verticalMargin;
            }
        }

        private void VegasBOT_FormClosing(object sender, FormClosingEventArgs e)
        {
            autoit = null;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtUrl.Text = Clipboard.GetText();            
            txtUrl.Focus();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (otherStrategyData != null)
            {
                var data = otherStrategyData.Last().Number;
                for (int i = 2; i < data.Count; i++)
                {
                    grpGameInfo.Controls[string.Format("lbl{0}", i - 2)].Text = data[i].NotHintTime.ToString();
                }
            }
            
            lblC1.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.C1).NotHintTime.ToString();
            lblC2.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.C2).NotHintTime.ToString();
            lblC3.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.C3).NotHintTime.ToString();

            lblD1.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.D1).NotHintTime.ToString();
            lblD2.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.D2).NotHintTime.ToString();
            lblD3.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.D3).NotHintTime.ToString();

            lblHigh.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.HIGH).NotHintTime.ToString();
            lblLow.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.LOW).NotHintTime.ToString();

            lblEven.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.EVEN).NotHintTime.ToString();
            lblOdd.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.ODD).NotHintTime.ToString();

            lblBlack.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.BLACK).NotHintTime.ToString();
            lblRed.Text = otherStrategyData.FirstOrDefault(t => t.SubStrategy == SUB_STRATEGY.RED).NotHintTime.ToString();

            if (LAST_WIN_NUMBER >= 0)
                lblLastNumber.Text = LAST_WIN_NUMBER.ToString();
            else
                lblLastNumber.Text = "";

            lblTotalWinnings.Text = BalanceAmount.ToString("#,##0");

            if (Game_Busy)
            {
                btnStop_Click(btnStop, new EventArgs());
            }
        }
    }
}
